﻿using System;
using System.Collections;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using GeneralLibs;
using CustomSecurity;

namespace Lists
{
    public class NhoGiaMuaBanNhapXuat : DoiTuong
    {
        #region DoiTuongNghiepVuID property
        public Guid DoiTuongNghiepVuID
        {
            get
            {
                return (Guid)_DataRow["DoiTuongNghiepVuID"];
            }
            set
            {
                _DataRow["DoiTuongNghiepVuID"] = value;
            }
        }
        #endregion

        #region VatTuHangHoaID property
        public Guid VatTuHangHoaID
        {
            get
            {
                return (Guid)_DataRow["VatTuHangHoaID"];
            }
            set
            {
                _DataRow["VatTuHangHoaID"] = value;
            }
        }
        #endregion

        #region ChietKhauMua property
        public decimal ChietKhauMua
        {
            get
            {
                return (decimal)_DataRow["ChietKhauMua"];
            }
            set
            {
                _DataRow["ChietKhauMua"] = value;
            }
        }
        #endregion

        #region ChietKhauBan property
        public decimal ChietKhauBan
        {
            get
            {
                return (decimal)_DataRow["ChietKhauBan"];
            }
            set
            {
                _DataRow["ChietKhauBan"] = value;
            }
        }
        #endregion

        #region ThoiGian property
        public DateTime ThoiGian
        {
            get
            {
                return (DateTime)_DataRow["ThoiGian"];
            }
            set
            {
                _DataRow["ThoiGian"] = (DateTime)System.DateTime.Now;
            }
        }
        #endregion

        #region LoaiChungTuID property
        public Guid LoaiChungTuID
        {
            get
            {
                return (Guid)_DataRow["LoaiChungTuID"];
            }
            set
            {
                _DataRow["LoaiChungTuID"] = value;
            }
        }
        #endregion

        #region PhuongThucThanhToanID property
        public Guid PhuongThucThanhToanID
        {
            get
            {
                return (Guid)_DataRow["PhuongThucThanhToanID"];
            }
            set
            {
                _DataRow["PhuongThucThanhToanID"] = value;
            }
        }
        #endregion

        #region ThueSuatID property
        public Guid ThueSuatID
        {
            get
            {
                return (Guid)_DataRow["ThueSuatID"];
            }
            set
            {
                _DataRow["ThueSuatID"] = value;
            }
        }
        #endregion

       public NhoGiaMuaBanNhapXuat(DataRow dataRow)
            : base(dataRow)
        {
        }
    }

    public class DanhMucNhoGiaMuaBanNhapXuat : DanhMucDoiTuong, IEnumerable
    {
        #region Instance property: Singleton Design pattern
        private static DanhMucNhoGiaMuaBanNhapXuat _Instance;
        public static DanhMucNhoGiaMuaBanNhapXuat Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new DanhMucNhoGiaMuaBanNhapXuat();
                }
                return _Instance;
            }
        }
        #endregion

        #region override TableName property
        public override string TableName
        {
            get
            {
                return "NhoGiaMuaBanNhapXuat";
            }
        }
        #endregion 

        #region Methods required by IEnumerable (use for foreach)
        public IEnumerator GetEnumerator()
        {
            return new TokenEnumerator(this);
        }

        private class TokenEnumerator : IEnumerator
        {
            private int _Position = -1;
            DanhMucDoiTuong _Dstk;

            public TokenEnumerator(DanhMucDoiTuong dstk)
            {
                _Dstk = dstk;
            }

            // Declare the MoveNext method required by IEnumerator:
            public bool MoveNext()
            {
                if (_Position < _Dstk.DataView.Count - 1)
                {
                    _Position++;
                    return true;
                }
                else
                {
                    return false;
                }
            }

            // Declare the Reset method required by IEnumerator:
            public void Reset()
            {
                _Position = -1;
            }

            // Declare the Current property required by IEnumerator:
            public object Current
            {
                get
                {
                    return new NhoGiaMuaBanNhapXuat((_Dstk.DataView[_Position].Row));
                }
            }
        }
        #endregion

        public NhoGiaMuaBanNhapXuat this[int index]
        {
            get
            {
                if (0 <= index && index <= this.Count)
                {
                    return new NhoGiaMuaBanNhapXuat(DataTable.Rows[index]);
                }
                else
                {
                    return null;
                }
            }
        }

        public NhoGiaMuaBanNhapXuat NewDoiTuong()
        {
            return new NhoGiaMuaBanNhapXuat(DataTable.NewRow());
        }

        public NhoGiaMuaBanNhapXuat GetByProperty(string property, object value)
        {
            try
            {
                DataRow[] rows = GetDataRows(property, value);
                if (rows.Length > 0) return new NhoGiaMuaBanNhapXuat(rows[0]);
                else return null;
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        public NhoGiaMuaBanNhapXuat GetByID(Guid objID)
        {
            return GetByProperty("ID", objID);
        }

        public NhoGiaMuaBanNhapXuat GetByIDsForNhoGia(Guid doiTuongNghiepVuID, Guid vatTuHangHoaID)
        {
            try
            {
                string filterExpression = string.Format("VatTuHangHoaID = '{0}' AND DoiTuongNghiepVuID = '{1}'", vatTuHangHoaID, doiTuongNghiepVuID);
                DataRow[] rows = DataTable.Select(filterExpression);

                if (rows.Length > 0) return new NhoGiaMuaBanNhapXuat(rows[0]);
                else return null;
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        public NhoGiaMuaBanNhapXuat GetByIDsForNhoPhuongThucThanhToan_Thue(Guid loaiChungTuID, Guid doiTuongNghiepVuID)
        {
            try
            {
                string filterExpression = string.Format("LoaiChungTuID = '{0}' AND DoiTuongNghiepVuID = '{1}'", loaiChungTuID, doiTuongNghiepVuID);
                DataRow[] rows = DataTable.Select(filterExpression);

                if (rows.Length > 0) return new NhoGiaMuaBanNhapXuat(rows[0]);
                else return null;
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        public DanhMucNhoGiaMuaBanNhapXuat GetByDoiTuongNghiepVuID(Guid doiTuongNghiepVuID)
        {
            try
            {
                string filterExpresstion = string.Format("DoiTuongNghiepVuID = '{0}'",doiTuongNghiepVuID);
                DanhMucNhoGiaMuaBanNhapXuat obj = new DanhMucNhoGiaMuaBanNhapXuat();
                obj.DataView = new DataView(DanhMucNhoGiaMuaBanNhapXuat.Instance.DataTable, filterExpresstion, "", DataViewRowState.CurrentRows);
                return obj;
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        public void AutoUpdateTheoLichSuMuaBan(Guid doiTuongNghiepVuID, Guid vatTuHangHoaID)
        {
            //Dùng để tự động cập nhật lại bảng nhớ giá theo hóa đơn gần nhât cho từng dòng 1.
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                decimal chietKhauMua = 0, chietKhauBan = 0;

                cmd.CommandText = string.Format("SELECT TOP 1 C.Value8 ChietKhauBan  \n " +
                                                "FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n " +
                                                "     INNER JOIN KhoanMucChungTu C ON C.ChungTuID = B.ChungTuID \n " +
                                                "     INNER JOIN LoaiChungTu LCT ON A.LoaiChungTuID = LCT.ID \n " +
                                                "WHERE	A.DoiTuongNghiepVu1ID = '{0}' \n " +
                                                "       AND VatTuHangHoa1ID = '{1}' \n " +
                                                "       AND LCT.Ma = 'HoaDonBanHang' \n " +
                                                "ORDER BY A.Ngay DESC \n "
                                                , doiTuongNghiepVuID, vatTuHangHoaID);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read()) chietKhauBan = (decimal)dr["ChietKhauBan"];
                dr.Close();

                cmd.CommandText = string.Format("SELECT TOP 1 C.Value8 ChietKhauMua  \n " +
                                                "FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n " +
                                                "     INNER JOIN KhoanMucChungTu C ON C.ChungTuID = B.ChungTuID \n " +
                                                "     INNER JOIN LoaiChungTu LCT ON A.LoaiChungTuID = LCT.ID \n " +
                                                "WHERE	A.DoiTuongNghiepVu1ID = '{0}' \n " +
                                                "       AND VatTuHangHoa1ID = '{1}' \n " +
                                                "       AND LCT.Ma = 'HoaDonMuaHang' \n " +
                                                "ORDER BY A.Ngay DESC \n "
                                                , doiTuongNghiepVuID, vatTuHangHoaID);
                dr = cmd.ExecuteReader();
                if (dr.Read()) chietKhauMua = (decimal)dr["ChietKhauMua"];
                dr.Close();

                NhoGiaMuaBanNhapXuat nhoGiaMuaBanNhapXuat = this.GetByIDsForNhoGia(doiTuongNghiepVuID, vatTuHangHoaID);
                if (0 < chietKhauBan && chietKhauBan <= 100)
                {
                    if (nhoGiaMuaBanNhapXuat == null)
                    {
                        nhoGiaMuaBanNhapXuat = this.NewDoiTuong();
                        nhoGiaMuaBanNhapXuat.ThoiGian = System.DateTime.Now;
                        nhoGiaMuaBanNhapXuat.VatTuHangHoaID = vatTuHangHoaID;
                        nhoGiaMuaBanNhapXuat.DoiTuongNghiepVuID = doiTuongNghiepVuID;
                        nhoGiaMuaBanNhapXuat.ChietKhauBan = chietKhauBan;
                        nhoGiaMuaBanNhapXuat.InsertToDB(cmd);
                    }
                    else
                    {
                        nhoGiaMuaBanNhapXuat.ThoiGian = System.DateTime.Now;
                        nhoGiaMuaBanNhapXuat.VatTuHangHoaID = vatTuHangHoaID;
                        nhoGiaMuaBanNhapXuat.DoiTuongNghiepVuID = doiTuongNghiepVuID;
                        nhoGiaMuaBanNhapXuat.ChietKhauBan = chietKhauBan;
                        nhoGiaMuaBanNhapXuat.UpdateToDB(cmd);
                    }
                }
               
                if (0 < chietKhauMua && chietKhauMua <= 100)
                {
                    if (nhoGiaMuaBanNhapXuat == null)
                    {
                        nhoGiaMuaBanNhapXuat = this.NewDoiTuong();
                        nhoGiaMuaBanNhapXuat.ThoiGian = System.DateTime.Now;
                        nhoGiaMuaBanNhapXuat.VatTuHangHoaID = vatTuHangHoaID;
                        nhoGiaMuaBanNhapXuat.DoiTuongNghiepVuID = doiTuongNghiepVuID;
                        nhoGiaMuaBanNhapXuat.ChietKhauMua = chietKhauMua;
                        nhoGiaMuaBanNhapXuat.InsertToDB(cmd);
                    }
                    else
                    {
                        nhoGiaMuaBanNhapXuat.ThoiGian = System.DateTime.Now;
                        nhoGiaMuaBanNhapXuat.VatTuHangHoaID = vatTuHangHoaID;
                        nhoGiaMuaBanNhapXuat.DoiTuongNghiepVuID = doiTuongNghiepVuID;
                        nhoGiaMuaBanNhapXuat.ChietKhauMua = chietKhauMua;
                        nhoGiaMuaBanNhapXuat.UpdateToDB(cmd);
                    }
                }

                if ((chietKhauBan <= 0 || chietKhauBan > 100) && (chietKhauMua <= 0 || chietKhauMua > 100))
                {
                    if (nhoGiaMuaBanNhapXuat != null) nhoGiaMuaBanNhapXuat.DeleteFromDB();
                }
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new CustomException("Lỗi:" + ex.ToString());
                }
            }
            finally
            {
                con.Close();
            }
        }

        public void SaveSingleRow(Guid doiTuongNghiepVuID, Guid vatTuHangHoaID, bool isMua ,decimal chietKhau)
        {
            //Lưu nhớ giá mua bán nhập xuất theo từng dòng
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            NhoGiaMuaBanNhapXuat nhoGiaMuaBanNhapXuat = DanhMucNhoGiaMuaBanNhapXuat.Instance.GetByIDsForNhoGia(doiTuongNghiepVuID, vatTuHangHoaID);

            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                if (nhoGiaMuaBanNhapXuat == null)
                {
                    nhoGiaMuaBanNhapXuat = DanhMucNhoGiaMuaBanNhapXuat.Instance.NewDoiTuong();
                    nhoGiaMuaBanNhapXuat.ThoiGian = System.DateTime.Now;
                    nhoGiaMuaBanNhapXuat.VatTuHangHoaID = vatTuHangHoaID;
                    nhoGiaMuaBanNhapXuat.DoiTuongNghiepVuID = doiTuongNghiepVuID;
                    if (isMua) nhoGiaMuaBanNhapXuat.ChietKhauMua = chietKhau;
                    else nhoGiaMuaBanNhapXuat.ChietKhauBan = chietKhau;

                    nhoGiaMuaBanNhapXuat.InsertToDB(cmd);
                }
                else
                {
                    if (isMua)
                    {
                        if (nhoGiaMuaBanNhapXuat.ChietKhauMua == chietKhau) return;
                    }
                    else
                    {
                        if (nhoGiaMuaBanNhapXuat.ChietKhauBan == chietKhau) return;
                    }
                    nhoGiaMuaBanNhapXuat.ThoiGian = System.DateTime.Now;
                    nhoGiaMuaBanNhapXuat.DoiTuongNghiepVuID = doiTuongNghiepVuID;
                    if (isMua) nhoGiaMuaBanNhapXuat.ChietKhauMua = chietKhau;
                    else nhoGiaMuaBanNhapXuat.ChietKhauBan = chietKhau;

                    nhoGiaMuaBanNhapXuat.UpdateToDB(cmd);
                }
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
            finally
            {
                con.Close();
            }
        }

        public void DeleteFromDB(Hashtable htNhoGia, bool isMua)   
        {
            //Xóa các row trong dtNhoGia khỏi CSDL
            foreach (DictionaryEntry entry in htNhoGia)
            {
                NhoGiaMuaBanNhapXuat nhoGiaMuaBanNhapXuat = DanhMucNhoGiaMuaBanNhapXuat.Instance.GetByIDsForNhoGia((Guid)entry.Key, (Guid)entry.Value);
                if (nhoGiaMuaBanNhapXuat != null) nhoGiaMuaBanNhapXuat.DeleteFromDB();

                AutoUpdateTheoLichSuMuaBan((Guid)entry.Key, (Guid)entry.Value);
            }
        }
    }
}
